package org.fcitmuk.openclinica;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import org.fcitmuk.db.util.Persistent;
import org.fcitmuk.db.util.PersistentHelper;

/**
 * This class encapsulates a list of subjects database field values.
 * 
 * @author Daniel
 *
 */
public class SubjectFieldValueList implements Persistent{

	private Vector values;

	public SubjectFieldValueList(){

	}

	public SubjectFieldValueList(Vector values) {
		super();
		this.values = values;
	}

	public Vector getValues() {
		return values;
	}

	public void setValues(Vector values) {
		this.values = values;
	}

	public void addValue(SubjectFieldValue value){
		if(values == null)
			values = new Vector();
		values.addElement(value);
	}

	public void addSubjectFields(Vector valueList){
		if(valueList != null){
			if(values == null)
				values = valueList;
			else{
				for(int i=0; i<valueList.size(); i++ )
					this.values.addElement(valueList.elementAt(i));
			}
		}
	}

	public int size(){
		if(getValues() == null)
			return 0;
		return getValues().size();
	}

	public SubjectFieldValue getValue(int index){
		return (SubjectFieldValue)getValues().elementAt(index);
	}

	public Object getPatintFiledValue(int fieldId,Integer subjectId){
		for(int i=0; i<size(); i++){
			SubjectFieldValue fieldVal = getValue(i);
			if(fieldVal.getFieldId() == fieldId && fieldVal.getSubjectId() == subjectId.intValue())
				return fieldVal.getValue(); 
		}
		return null;
	}

	/** 
	 * Reads the subject field value collection object from the supplied stream.
	 * 
	 * @param dis - the stream to read from.
	 * @throws IOException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public void read(DataInputStream dis) throws IOException, InstantiationException, IllegalAccessException {
		setValues(PersistentHelper.read(dis,new SubjectFieldValue().getClass(),dis.readInt()));
	}

	/** 
	 * Writes the subject field value collection object to the supplied stream.
	 * 
	 * @param dos - the stream to write to.
	 * @throws IOException
	 */
	public void write(DataOutputStream dos) throws IOException {
		PersistentHelper.write(getValues(), dos,0);
	}
}
